<template>
  <div class="tag-management-system">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>通用标签管理</h1>
        <p>统一管理商品标签和文章标签，支持多类型标签的共享使用</p>
      </div>

      <!-- 操作栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <div class="search-box">
            <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <circle cx="11" cy="11" r="8" />
              <path d="m21 21-4.35-4.35" />
            </svg>
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索标签名称或描述..."
              class="search-input"
            />
          </div>

          <div class="filter-group">
            <select v-model="filterType" class="filter-select">
              <option value="">全部类型</option>
              <option value="1">分类标签</option>
              <option value="2">属性标签</option>
              <option value="3">品牌标签</option>
              <option value="4">促销标签</option>
            </select>

            <select v-model="filterAssociationType" class="filter-select">
              <option value="">全部关联类型</option>
              <option value="product">仅商品关联</option>
              <option value="article">仅文章关联</option>
              <option value="both">商品+文章关联</option>
            </select>

            <select v-model="filterStatus" class="filter-select">
              <option value="">全部状态</option>
              <option value="active">启用</option>
              <option value="inactive">禁用</option>
            </select>
          </div>
        </div>

        <div class="toolbar-right">
          <!-- 批量操作按钮 -->
          <div v-if="selectedTags.length > 0" class="batch-actions-inline">
            <el-button class="btn btn-success btn-sm" @click="batchEnable">
              <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <polyline points="20,6 9,17 4,12" />
              </svg>
              批量启用 ({{ selectedTags.length }})
            </el-button>
            <el-button class="btn btn-warning btn-sm" @click="batchDisable">
              <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <circle cx="12" cy="12" r="10" />
                <line x1="15" y1="9" x2="9" y2="15" />
                <line x1="9" y1="9" x2="15" y2="15" />
              </svg>
              批量禁用 ({{ selectedTags.length }})
            </el-button>
            <el-button class="btn btn-danger btn-sm" @click="batchDelete">
              <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <polyline points="3,6 5,6 21,6" />
                <path d="M19,6v14a2,2,0,0,1-2,2H7a2,2,0,0,1-2-2V6m3,0V4a2,2,0,0,1,2-2h4a2,2,0,0,1,2,2V6" />
              </svg>
              批量删除 ({{ selectedTags.length }})
            </el-button>
          </div>
          <el-button class="btn btn-primary" @click="addTag">
            <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <line x1="12" y1="5" x2="12" y2="19" />
              <line x1="5" y1="12" x2="19" y2="12" />
            </svg>
            添加标签
          </el-button>
        </div>
      </div>

      <!-- 标签统计概览 -->
      <div class="stats-overview">
        <div class="stat-card">
          <div class="stat-icon blue">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z" />
              <line x1="7" y1="7" x2="7.01" y2="7" />
            </svg>
          </div>
          <div class="stat-content">
            <p class="stat-label">总标签数</p>
            <p class="stat-value">{{ totalTags }}</p>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon green">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
              <polyline points="22,4 12,14.01 9,11.01" />
            </svg>
          </div>
          <div class="stat-content">
            <p class="stat-label">商品专用标签</p>
            <p class="stat-value">{{ productOnlyTags }}</p>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon orange">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
              <rect x="9" y="9" width="6" height="6" />
            </svg>
          </div>
          <div class="stat-content">
            <p class="stat-label">通用标签</p>
            <p class="stat-value">{{ universalTags }}</p>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon purple">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <polyline points="23,6 13.5,15.5 8.5,10.5 1,18" />
              <polyline points="17,6 23,6 23,12" />
            </svg>
          </div>
          <div class="stat-content">
            <p class="stat-label">总关联数</p>
            <p class="stat-value">{{ totalAssociations }}</p>
          </div>
        </div>
      </div>

      <!-- 标签表格 -->
      <el-table
        ref="multipleTableRef"
        v-loading="loading"
        :data="filteredTags"
        row-key="id"
        width="100%"
        element-loading-text="加载中..."
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="标签信息">
          <template #default="scope">
            <div class="tag-info">
              <div class="tag-color" :style="{ backgroundColor: scope.row.color }" />
              <div class="tag-details">
                <div class="tag-name">{{ scope.row.name }}</div>
                <div class="tag-description">{{ scope.row.description }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <span class="type-badge" :class="getTypeBadgeClass(scope.row.type)">
              {{ getTypeBadge(scope.row.type) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="scope" label="适用范围" width="120">
          <template #default="scope">
            <span class="scope-badge" :class="getScopeBadgeClass(scope.row.type)">
              {{ getTagScope(scope.row.type) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="权重">
          <template #default="scope">
            <div class="weight-display">
              <div class="weight-bar">
                <div class="weight-fill" :style="{ width: (scope.row.weight / 10) * 100 + '%' }" />
              </div>
              <span class="weight-value">{{ scope.row.weight }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="associations" label="关联内容" align="center">
          <template #default="scope">
            <div class="association-info">
              <div class="association-counts">
                <span v-if="canAssociateProduct(scope.row.type)" class="count-item">
                  商品: {{ scope.row.productCount || 0 }}
                </span>
                <span v-if="canAssociateArticle(scope.row.type)" class="count-item">
                  文章: {{ scope.row.articleCount || 0 }}
                </span>
              </div>
              <div class="manage-buttons">
                <el-button
                  v-if="canAssociateProduct(scope.row.type)"
                  class="btn-link"
                  @click="handleManageProducts(scope.row)"
                >
                  管理商品
                </el-button>
                <el-button
                  v-if="canAssociateArticle(scope.row.type)"
                  class="btn-link"
                  @click="handleManageArticles(scope.row)"
                >
                  管理文章
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#4caf50"
              inactive-color="#f44336"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="170" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button class="btn-icon" title="编辑" @click="editTag(scope.row)">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                  <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
                </svg>
              </el-button>
              <el-button class="btn-icon" title="复制" @click="duplicateTag(scope.row)">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
                </svg>
              </el-button>
              <el-button class="btn-icon danger" title="删除" @click="deleteTag(scope.row)">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <polyline points="3,6 5,6 21,6" />
                  <path d="M19,6v14a2,2,0,0,1-2,2H7a2,2,0,0,1-2-2V6m3,0V4a2,2,0,0,1,2-2h4a2,2,0,0,1,2,2V6" />
                </svg>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑标签模态框 -->
      <el-dialog
        v-model="showAddModal"
        :title="showAddModal ? '添加标签' : '编辑标签'"
        width="500px"
        @close="closeModal"
      >
        <el-form ref="tagFormRef" :model="currentTag" :rules="tagRules" label-width="100px">
          <el-form-item label="标签名称" prop="name">
            <el-input v-model="currentTag.name" placeholder="请输入标签名称" />
          </el-form-item>
          <el-form-item label="标签类型" prop="type">
            <el-select v-model="currentTag.type" placeholder="请选择类型">
              <el-option label="商品标签" :value="1" />
              <el-option label="文章标签" :value="2" />
              <el-option label="商品+文章标签" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="适用范围">
            <div class="scope-info">
              <span class="scope-text">{{ getTagScopeDescription(currentTag.type) }}</span>
            </div>
          </el-form-item>
          <el-form-item label="标签描述" prop="description">
            <el-input
              v-model="currentTag.description"
              type="textarea"
              :rows="3"
              placeholder="请输入标签描述"
            />
          </el-form-item>
          <el-form-item label="标签颜色" prop="color">
            <el-color-picker v-model="currentTag.color" />
          </el-form-item>
          <el-form-item label="权重 (1-10)" prop="weight">
            <el-slider v-model="currentTag.weight" :min="1" :max="10" show-input />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="currentTag.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="currentTag.sort" :min="0" placeholder="排序值，数字越小越靠前" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="closeModal">取消</el-button>
          <el-button type="primary" @click="saveTag">
            {{ showAddModal ? "添加" : "保存" }}
          </el-button>
        </template>
      </el-dialog>
      <!-- 删除标签确认模态框 -->
      <el-dialog
        v-model="showDeleteModal"
        title="确认删除"
        width="400px"
        center
        @close="showDeleteModal = false"
      >
        <div class="confirm-icon">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path
              d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"
            />
            <line x1="12" y1="9" x2="12" y2="13" />
            <line x1="12" y1="17" x2="12.01" y2="17" />
          </svg>
        </div>
        <p v-if="tagToDelete">
          您确定要删除标签 "{{ tagToDelete.name }}" 吗？<br />
          <span v-if="canAssociateProduct(tagToDelete.type) && tagToDelete.productCount > 0">
            该标签关联了 {{ tagToDelete.productCount }} 个商品，
          </span>
          <span v-if="canAssociateArticle(tagToDelete.type) && tagToDelete.articleCount > 0">
            该标签关联了 {{ tagToDelete.articleCount }} 个文章，
          </span>
          删除后将解除所有关联。
        </p>
        <p v-else-if="selectedTags.length > 0">
          您确定要删除选中的
          {{ selectedTags.length }} 个标签吗？此操作无法撤销。
        </p>
        <template #footer>
          <el-button @click="showDeleteModal = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </template>
      </el-dialog>
      <!-- 商品关联管理 -->
      <DualTableAssociation
        v-model="showProductManageModal"
        :target-id="currentManageTag && currentManageTag.id"
        dialog-title="标签商品关联管理"
        left-table-title="已关联商品"
        right-table-title="可关联商品"
        confirm-text="关联商品"
        :left-table-columns="linkedProductColumns"
        :right-table-columns="availableProductColumns"
        search-field="name"
        id-field="id"
        name-field="商品名"
        @get-linked-items="handleGetLinkedProducts"
        @get-available-items="handleGetAvailableProducts"
        @update-association="handleUpdateProductAssociation"
        @add-association="handleAddProductAssociation"
        @remove-association="handleRemoveProductAssociation"
        @confirm="handleAssociationConfirm"
        @cancel="handleAssociationCancel"
      />

      <!-- 文章关联管理 -->
      <DualTableAssociation
        v-model="showArticleManageModal"
        :target-id="currentManageTag && currentManageTag.id"
        dialog-title="标签文章关联管理"
        left-table-title="已关联文章"
        right-table-title="可关联文章"
        confirm-text="关联文章"
        :left-table-columns="linkedArticleColumns"
        :right-table-columns="availableArticleColumns"
        search-field="title"
        id-field="id"
        name-field="文章"
        @get-linked-items="handleGetLinkedArticles"
        @get-available-items="handleGetAvailableArticles"
        @update-association="handleUpdateArticleAssociation"
        @add-association="handleAddArticleAssociation"
        @remove-association="handleRemoveArticleAssociation"
        @confirm="handleAssociationConfirm"
        @cancel="handleAssociationCancel"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import DualTableAssociation from "./components/DualTableAssociation/index.vue";
import {
  createTag,
  batchDeleteTags,
  getTags as fetchTags,
  updateTag,
  updateTagStatus,
  getGoodsByTagId,
  batchUpdateTagsStatus,
  assignTagsToProduct,
  removeTagFromProduct,
  getArticlesByTagId,
  assignTagsToArticle,
  removeTagFromArticle
} from "@/api/tag-management";
import { getGoodsList } from "@/api/goods";
import { getArticleList } from "@/api/article";

defineOptions({
  name: "TagManagementSystem"
});

// 搜索和筛选
const searchQuery = ref("");
const filterType = ref("");
const filterAssociationType = ref("");
const filterStatus = ref("");

// 标签列表查询参数
const tagQueryParams = reactive({
  name: "",
  type: null,
  status: "",
  page: 1,
  pageSize: 10,
  include_relations: true
});

// 模态框状态
const showAddModal = ref(false); // 添加标签模态框状态
const showDeleteModal = ref(false); // 删除标签模态框状态
const showProductManageModal = ref(false); // 商品关联管理模态框状态
const showArticleManageModal = ref(false); // 文章关联管理模态框状态

// 选择状态
const selectAll = ref(false);
const selectedTags = ref<number[]>([]);

// 当前操作的标签
const tagToDelete = ref<any>(null);
const currentManageTag = ref<any>(null);

// 表格列配置
const linkedProductColumns = reactive([
  { label: "商品编号", prop: "id", width: 110 },
  { label: "商品名称", prop: "name" },
  { label: "品牌", prop: "brand", width: 100 },
  { label: "价格", prop: "price", width: 80 }
]);

const availableProductColumns = reactive([
  { label: "商品编号", prop: "id", width: 110 },
  { label: "商品名称", prop: "name" },
  { label: "品牌", prop: "brand", width: 100 },
  { label: "价格", prop: "basePrice", width: 80 },
  { label: "创建时间", prop: "create_time", width: 120 }
]);

const linkedArticleColumns = reactive([
  { label: "文章ID", prop: "id", width: 80 },
  { label: "文章标题", prop: "title", width: 200 },
  { label: "分类", prop: "category_name", width: 100 },
  { label: "作者", prop: "author", width: 100 },
  { label: "状态", prop: "status", width: 80 },
  { label: "发布时间", prop: "published_date", width: 150 }
]);

const availableArticleColumns = reactive([
  { label: "文章ID", prop: "id", width: 80 },
  { label: "文章标题", prop: "title", width: 200 },
  { label: "分类", prop: "category_name", width: 100 },
  { label: "作者", prop: "author", width: 100 },
  { label: "状态", prop: "status", width: 80 },
  { label: "发布时间", prop: "published_date", width: 150 }
]);

// 商品管理相关数据（已迁移至 DualTableAssociation 组件内部处理）
const searchDebounceTimer = ref<any>(null); // 搜索防抖定时器
const loading = ref(false);

// 当前编辑的标签
const currentTag = reactive({
  id: null,
  name: "",
  description: "",
  type: 1, // 默认为商品标签
  color: "#3B82F6",
  weight: 5,
  status: 0,
  sort: 0,
  productCount: 0,
  articleCount: 0,
  create_time: new Date()
});

const tagFormRef = ref<any>(null);
const tagRules = reactive<any>({
  name: [
    { required: true, message: "请输入标签名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  type: [{ required: true, message: "请选择标签类型", trigger: "change" }]
});

// 标签数据 - 移除默认数据，改为从API获取
const tags = ref<any[]>([]);
const total = ref(0);

// Computed properties
const filteredTags = computed(() => {
  return [...tags.value].sort((a, b) => (a.sort || 0) - (b.sort || 0));
});

const totalTags = computed(() => tags.value.length);

// 商品专用标签：分类、属性、品牌
const productOnlyTags = computed(() => tags.value.filter(tag => [1, 2, 3].includes(tag.type)).length);

// 通用标签：促销标签可用于商品和文章
const universalTags = computed(() => tags.value.filter(tag => tag.type === 4).length);

const totalAssociations = computed(() =>
  tags.value.reduce((sum, tag) => sum + (tag.productCount || 0) + (tag.articleCount || 0), 0)
);

// Watchers
watch(selectAll, newVal => {
  if (newVal) {
    selectedTags.value = filteredTags.value.map(tag => tag.id);
  } else {
    selectedTags.value = [];
  }
});

watch(selectedTags, newVal => {
  selectAll.value = newVal.length === filteredTags.value.length && filteredTags.value.length > 0;
});

watch(searchQuery, newVal => {
  tagQueryParams.name = newVal;
  debounceGetTags();
});

watch(filterType, newVal => {
  tagQueryParams.type = parseInt(newVal);
  getTagsList();
});

watch(filterStatus, newVal => {
  tagQueryParams.status = newVal;
  getTagsList();
});

// Lifecycle hooks
onMounted(() => {
  getTagsList();
});

onUnmounted(() => {
  if (searchDebounceTimer.value) {
    clearTimeout(searchDebounceTimer.value);
  }
});

// 防抖获取标签列表
const debounceGetTags = () => {
  if (searchDebounceTimer.value) {
    clearTimeout(searchDebounceTimer.value);
  }
  searchDebounceTimer.value = setTimeout(() => {
    getTagsList();
  }, 300);
};
// 获取标签列表
const getTagsList = async () => {
  loading.value = true;
  try {
    const res: any = await fetchTags(tagQueryParams);

    console.log("标签列表返回信息：", res);
    if (res.code === 200) {
      tags.value = res.data.list || [];
      total.value = res.total || 0;
    } else {
      ElMessage.error(res.message || "获取标签列表失败");
    }
  } catch (error) {
    console.error("获取标签列表失败:", error);
    ElMessage.error("获取标签列表失败");
  } finally {
    loading.value = false;
  }
};
// 添加标签
const addTag = () => {
  showAddModal.value = true;
  Object.assign(currentTag, {
    id: null,
    name: "",
    description: "",
    type: 1,
    color: "#409EFF",
    weight: 5,
    status: 1,
    sort: 0,
    productCount: 0,
    articleCount: 0,
    create_time: new Date()
  });
  tagFormRef.value?.resetFields();
};
// 修改标签
const editTag = (tag: any) => {
  showAddModal.value = true; // 修复：应该显示添加模态框，因为是同一个模态框
  Object.assign(currentTag, tag);
};
// 复制标签
const duplicateTag = (tag: any) => {
  showAddModal.value = true;
  tagFormRef.value?.resetFields();
  Object.assign(currentTag, {
    ...tag,
    id: null,
    name: tag.name + " (副本)",
    productCount: 0,
    articleCount: 0,
    create_time: new Date()
  });
};
// 提交新增/修改标签表单
const saveTag = async () => {
  const valid = await tagFormRef.value?.validate();
  if (!valid) {
    ElMessage.error("请填写完整表单");
    return;
  }

  try {
    let res: any;
    if (currentTag.id) {
      // 编辑标签
      res = await updateTag(currentTag.id, currentTag);
    } else {
      // 添加标签
      res = await createTag(currentTag);
    }

    if (res.code === 200 || res.code === 201) {
      ElMessage.success(currentTag.id ? "更新成功" : "添加成功");
      await getTagsList();
      closeModal();
    } else {
      ElMessage.error(res.message || (currentTag.id ? "更新失败" : "添加失败"));
    }
  } catch (error) {
    console.error("保存标签失败:", error);
    ElMessage.error("保存失败");
  }
};
// 删除标签
const deleteTag = (tag: any) => {
  tagToDelete.value = tag;
  showDeleteModal.value = true;
};
// 确认删除操作
const confirmDelete = async () => {
  try {
    let deleteIds: number[] = [];

    if (tagToDelete.value) {
      // 删除单个标签
      deleteIds = [tagToDelete.value.id];
    } else if (selectedTags.value.length > 0) {
      // 批量删除
      deleteIds = selectedTags.value;
    }
    if (deleteIds.length === 0) {
      ElMessage.warning("没有要删除的标签");
      return;
    }

    const res = await batchDeleteTags(deleteIds);
    if (res.code === 200) {
      ElMessage.success("删除成功");
      await getTagsList();
      selectedTags.value = [];
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch (error) {
    console.error("删除标签失败:", error);
    ElMessage.error("删除失败");
  } finally {
    showDeleteModal.value = false;
    tagToDelete.value = null;
  }
};
// 处理更新标签状态
const handleStatusChange = async (row: any) => {
  try {
    const response = await updateTagStatus(row.id, row.status);
    if (response.code === 200) {
      ElMessage.success(response.message);
    } else {
      ElMessage.error("状态更新失败");
      row.status = row.status === 1 ? 0 : 1;
    }
  } catch (error) {
    ElMessage.error("请求出错");
    row.status = row.status === 1 ? 0 : 1;
  }
};
// 处理选择标签
const handleSelectionChange = (selection: any[]) => {
  selectedTags.value = selection.map(tag => tag.id);
  console.log("选中的标签：", selection);
};

// 批量启用操作
const batchEnable = async () => {
  if (selectedTags.value.length === 0) {
    ElMessage.warning("请先选择要启用的标签");
    return;
  }
  try {
    const res = await batchUpdateTagsStatus(selectedTags.value, 1);
    if (res.code === 200) {
      ElMessage.success("批量启用成功");
      await getTagsList();
      selectedTags.value = [];
    } else {
      ElMessage.error(res.message || "批量启用失败");
    }
  } catch (error) {
    console.error("批量启用失败:", error);
    ElMessage.error("批量启用失败");
  }
};
// 批量禁用操作
const batchDisable = async () => {
  if (selectedTags.value.length === 0) {
    ElMessage.warning("请先选择要禁用的标签");
    return;
  }
  try {
    const res = await batchUpdateTagsStatus(selectedTags.value, 0);
    if (res.code === 200) {
      ElMessage.success("批量禁用成功");
      await getTagsList();
      selectedTags.value = [];
    } else {
      ElMessage.error(res.message || "批量禁用失败");
    }
  } catch (error) {
    console.error("批量禁用失败:", error);
    ElMessage.error("批量禁用失败");
  }
};
// 批量删除操作
const batchDelete = () => {
  if (selectedTags.value.length === 0) {
    ElMessage.warning("请先选择要删除的标签");
    return;
  }
  showDeleteModal.value = true;
};

// 以下是 DualTableAssociation 相关的回调函数
// 商品关联相关
const handleGetLinkedProducts = async (query: any, callback: Function) => {
  try {
    const params = {
      targetId: query.targetId,
      pageNum: query.pageNum,
      pageSize: query.pageSize
    };
    if (query.name) {
      (params as any).name = query.name;
    }
    const response: any = await getGoodsByTagId(params);
    const result = {
      rows: response.data?.products || [],
      total: response.total || 0
    };
    callback(result);
  } catch (error) {
    console.error("获取已关联商品失败:", error);
    callback({ success: false });
  }
};
// 获取可关联商品
const handleGetAvailableProducts = async (query: any, callback: Function) => {
  try {
    const params = {
      page: query.pageNum,
      pageSize: query.pageSize
    };
    if (query.name) {
      (params as any).name = query.name;
    }
    if (query.excludeIds && query.excludeIds.length > 0) {
      (params as any).excludeIds = query.excludeIds;
    }
    const response: any = await getGoodsList(params);
    const result = {
      rows: response.data?.list || [],
      total: response.total || 0
    };
    callback(result);
  } catch (error) {
    console.error("获取可关联商品失败:", error);
    callback({ success: false });
  }
};
// 更新商品关联关系（兼容旧接口）
const handleUpdateProductAssociation = async (
  data: { targetId: number; associatedIds: number[] },
  callback: Function
) => {
  try {
    // 使用 assignTagsToProduct 设置完整的关联列表（覆盖现有关联）
    const response = await assignTagsToProduct(data.targetId, data.associatedIds);

    if (response.code === 200) {
      ElMessage.success("商品关联更新成功");
      callback(true);
      // 刷新标签列表以更新关联数量
      getTagsList();
    } else {
      ElMessage.error(response.message || "商品关联更新失败");
      callback(false);
    }
  } catch (error) {
    console.error("更新商品关联关系失败:", error);
    ElMessage.error("商品关联更新失败");
    callback(false);
  }
};

// 添加商品关联
const handleAddProductAssociation = async (
  data: { targetId: number; associatedIds: number[]; operation?: string },
  callback: Function
) => {
  try {
    // 使用 assignTagsToProduct 接口添加关联
    const response = await assignTagsToProduct(data.targetId, data.associatedIds);

    if (response.code === 200) {
      ElMessage.success("商品关联添加成功");
      callback(true);
      // 刷新标签列表以更新关联数量
      getTagsList();
    } else {
      ElMessage.error(response.message || "商品关联添加失败");
      callback(false);
    }
  } catch (error) {
    console.error("添加商品关联失败:", error);
    ElMessage.error("商品关联添加失败");
    callback(false);
  }
};

// 移除商品关联
const handleRemoveProductAssociation = async (
  data: { targetId: number; associatedIds: number[]; operation?: string },
  callback: Function
) => {
  try {
    // 使用 removeTagFromProduct 接口移除关联
    const response = await removeTagFromProduct(data.targetId, data.associatedIds);

    if (response.code === 200) {
      ElMessage.success("商品关联移除成功");
      callback(true);
      // 刷新标签列表以更新关联数量
      getTagsList();
    } else {
      ElMessage.error(response.message || "商品关联移除失败");
      callback(false);
    }
  } catch (error) {
    console.error("移除商品关联失败:", error);
    ElMessage.error("商品关联移除失败");
    callback(false);
  }
};

// 文章关联相关
const handleGetLinkedArticles = async (query: any, callback: Function) => {
  try {
    const params = {
      targetId: query.targetId,
      pageNum: query.pageNum,
      pageSize: query.pageSize
    };
    if (query.title) {
      (params as any).title = query.title;
    }
    const response: any = await getArticlesByTagId(params);
    const result = {
      rows: response.data?.articles || [],
      total: response.total || 0
    };
    callback(result);
  } catch (error) {
    console.error("获取已关联文章失败:", error);
    callback({ success: false });
  }
};
// 获取可关联文章
const handleGetAvailableArticles = async (query: any, callback: Function) => {
  try {
    const data = {
      page: query.pageNum,
      per_page: query.pageSize
    };
    if (query.title) {
      (data as any).title = query.title;
    }
    if (query.excludeIds && query.excludeIds.length > 0) {
      (data as any).excludeIds = query.excludeIds;
    }
    const response: any = await getArticleList(data);
    const result = {
      rows: response.data?.list || [],
      total: response.total || 0
    };
    callback(result);
  } catch (error) {
    console.error("获取可关联文章失败:", error);
    callback({ success: false });
  }
};
// 更新文章关联关系（兼容旧接口）
const handleUpdateArticleAssociation = async (
  data: { targetId: number; associatedIds: number[] },
  callback: Function
) => {
  try {
    // 使用 assignTagsToArticle 设置完整的关联列表（覆盖现有关联）
    const response = await assignTagsToArticle(data.targetId, data.associatedIds);

    if (response.code === 200) {
      ElMessage.success("文章关联更新成功");
      callback(true);
      // 刷新标签列表以更新关联数量
      getTagsList();
    } else {
      ElMessage.error(response.message || "文章关联更新失败");
      callback(false);
    }
  } catch (error) {
    console.error("更新文章关联关系失败:", error);
    ElMessage.error("文章关联更新失败");
    callback(false);
  }
};

// 添加文章关联
const handleAddArticleAssociation = async (
  data: { targetId: number; associatedIds: number[]; operation?: string },
  callback: Function
) => {
  try {
    // 使用 assignTagsToArticle 接口添加关联
    const response = await assignTagsToArticle(data.targetId, data.associatedIds);

    if (response.code === 200) {
      ElMessage.success("文章关联添加成功");
      callback(true);
      // 刷新标签列表以更新关联数量
      getTagsList();
    } else {
      ElMessage.error(response.message || "文章关联添加失败");
      callback(false);
    }
  } catch (error) {
    console.error("添加文章关联失败:", error);
    ElMessage.error("文章关联添加失败");
    callback(false);
  }
};

// 移除文章关联
const handleRemoveArticleAssociation = async (
  data: { targetId: number; associatedIds: number[]; operation?: string },
  callback: Function
) => {
  try {
    // 使用 removeTagFromArticle 接口移除关联
    const response = await removeTagFromArticle(data.targetId, data.associatedIds);

    if (response.code === 200) {
      ElMessage.success("文章关联移除成功");
      callback(true);
      // 刷新标签列表以更新关联数量
      getTagsList();
    } else {
      ElMessage.error(response.message || "文章关联移除失败");
      callback(false);
    }
  } catch (error) {
    console.error("移除文章关联失败:", error);
    ElMessage.error("文章关联移除失败");
    callback(false);
  }
};

const handleAssociationConfirm = () => {
  console.log("关联操作完成");
  getTagsList(); // 刷新标签列表以更新关联数量
};

const handleAssociationCancel = () => {
  console.log("取消关联操作");
};

// 管理商品关联
const handleManageProducts = (tag: any) => {
  currentManageTag.value = tag;
  showProductManageModal.value = true;
};

// 管理文章关联
const handleManageArticles = (tag: any) => {
  currentManageTag.value = tag;
  showArticleManageModal.value = true;
};

const closeModal = () => {
  showAddModal.value = false;
  Object.assign(currentTag, {
    id: null,
    name: "",
    description: "",
    type: 1,
    color: "#409EFF",
    weight: 5,
    status: 1,
    sort: 0,
    productCount: 0,
    articleCount: 0,
    create_time: new Date()
  });
  tagFormRef.value?.resetFields();
};

// 辅助方法-根据条件返回信息
const formatDate = (date: string | Date) => {
  if (!date) return "-";
  return new Date(date).toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit"
  });
};

const getTypeBadge = (type: number) => {
  const classType: { [key: number]: string } = {
    1: "商品标签",
    2: "文章标签",
    3: "商品+文章标签"
  };
  return classType[type] || "default";
};

const getTypeBadgeClass = (type: number) => {
  const classMap: { [key: number]: string } = {
    1: "category",
    2: "attribute",
    3: "brand"
  };
  return classMap[type] || "default";
};

// 标签类型相关方法
const canAssociateProduct = (type: number) => {
  // 所有类型的标签都可以关联商品
  return [1, 2, 3].includes(type);
};

const canAssociateArticle = (type: number) => {
  // 文章标签(2)和通用标签(3)可以关联文章
  return type === 2 || type === 3;
};

const getTagScope = (type: number) => {
  const scopeMap: { [key: number]: string } = {
    1: "仅商品",
    2: "仅文章",
    3: "商品+文章"
  };
  return scopeMap[type] || "未知";
};

const getScopeBadgeClass = (type: number) => {
  const classMap: { [key: number]: string } = {
    1: "product-only",
    2: "product-only",
    3: "universal"
  };
  return classMap[type] || "default";
};

const getTagScopeDescription = (type: number) => {
  const descriptions: { [key: number]: string } = {
    1: "仅适用于商品",
    2: "仅适用于文章",
    3: "仅适用于商品+文章"
  };
  return descriptions[type] || "请选择标签类型";
};
</script>

<style scoped>
/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (width <= 1024px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .toolbar-left,
  .toolbar-right {
    justify-content: center;
  }

  .search-box {
    min-width: auto;
  }

  .form-row {
    grid-template-columns: 1fr;
  }

  .stats-content {
    grid-template-columns: 1fr;
  }
}

@media (width <= 768px) {
  .tag-management-system {
    padding: 16px;
  }

  .stats-overview {
    grid-template-columns: 1fr;
  }

  .tags-table {
    font-size: 14px;
  }

  .tags-table th,
  .tags-table td {
    padding: 8px 12px;
  }

  .modal {
    width: 95%;
    margin: 20px;
  }

  .modal-header,
  .modal-body {
    padding: 16px;
  }

  .batch-actions {
    flex-direction: column;
    gap: 12px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .product-search {
    flex-direction: column;
  }
}

@media (width <= 480px) {
  .tag-info {
    flex-direction: column;
    align-items: flex-start;
  }

  .tag-color {
    margin-bottom: 8px;
  }

  .weight-display {
    flex-direction: column;
    align-items: flex-start;
  }

  .product-count {
    align-items: flex-start;
  }

  .filter-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
    width: 96%;
  }
}

* {
  box-sizing: border-box;
}

.tag-management-system {
  min-height: 100vh;
  padding: 0 24px 24px;
  background-color: #f5f5f5;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px;
  font-size: 28px;
  font-weight: bold;
  color: #1a1a1a;
}

.page-header p {
  margin: 0;
  color: #666;
}

/* 工具栏 */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  margin-bottom: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgb(0 0 0 / 10%);
}

.toolbar-left {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

.search-box {
  position: relative;
  min-width: 250px;
}

.search-icon {
  position: absolute;
  top: 50%;
  left: 12px;
  width: 16px;
  height: 16px;
  color: #999;
  transform: translateY(-50%);
}

.search-input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.search-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgb(0 123 255 / 25%);
}

.filter-group {
  display: flex;
  gap: 12px;
}

.filter-select {
  min-width: 120px;
  padding: 8px 12px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.filter-select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgb(0 123 255 / 25%);
}

/* 按钮样式 */
.btn {
  display: inline-flex;
  align-items: center;
  padding: 8px 16px;
  font-size: 14px;
  text-decoration: none;
  cursor: pointer;
  border: none;
  border-radius: 6px;
  transition: all 0.2s;
}

.btn .icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-primary {
  color: white;
  background-color: #007bff;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-success {
  color: white;
  background-color: #28a745;
}

.btn-success:hover {
  background-color: #1e7e34;
}

.btn-warning {
  color: #212529;
  background-color: #ffc107;
}

.btn-warning:hover {
  background-color: #e0a800;
}

.btn-danger {
  color: white;
  background-color: #dc3545;
}

.btn-danger:hover {
  background-color: #c82333;
}

.btn-link {
  padding: 0;
  font-size: 12px;
  color: #007bff;
  text-decoration: underline;
  cursor: pointer;
  background: none;
  border: none;
}

.btn-link:hover {
  color: #0056b3;
}

/* 统计概览 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgb(0 0 0 / 10%);
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  margin-right: 16px;
  border-radius: 8px;
}

.stat-icon svg {
  width: 24px;
  height: 24px;
}

.stat-icon.blue {
  color: #1976d2;
  background-color: #e3f2fd;
}

.stat-icon.green {
  color: #388e3c;
  background-color: #e8f5e8;
}

.stat-icon.orange {
  color: #f57c00;
  background-color: #fff3e0;
}

.stat-icon.purple {
  color: #7b1fa2;
  background-color: #f3e5f5;
}

.stat-content {
  flex: 1;
}

.stat-label {
  margin: 0 0 4px;
  font-size: 14px;
  color: #666;
}

.stat-value {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #1a1a1a;
}

/* 表格样式 */
.table-container {
  overflow: hidden;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgb(0 0 0 / 10%);
}

.tags-table {
  width: 100%;
  border-collapse: collapse;
}

.tags-table th {
  padding: 12px 16px;
  font-size: 12px;
  font-weight: 600;
  color: #495057;
  text-align: left;
  text-transform: uppercase;
  letter-spacing: 1px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
}

.tags-table td {
  padding: 16px;
  vertical-align: middle;
  border-bottom: 1px solid #dee2e6;
}

.tags-table tr:hover {
  background-color: #f8f9fa;
}

.tag-info {
  display: flex;
  align-items: center;
}

.tag-color {
  flex-shrink: 0;
  width: 16px;
  height: 16px;
  margin-right: 12px;
  border-radius: 50%;
}

.tag-details {
  flex: 1;
}

.tag-name {
  margin-bottom: 4px;
  font-weight: 600;
  color: #1a1a1a;
}

.tag-description {
  font-size: 14px;
  color: #666;
}

.type-badge {
  display: inline-block;
  padding: 4px 8px;
  font-size: 12px;
  font-weight: 500;
  border-radius: 4px;
}

.type-badge.category {
  color: #1976d2;
  background-color: #e3f2fd;
}

.type-badge.attribute {
  color: #388e3c;
  background-color: #e8f5e8;
}

.type-badge.brand {
  color: #7b1fa2;
  background-color: #f3e5f5;
}

.type-badge.promotion {
  color: #f57c00;
  background-color: #fff3e0;
}

.type-badge.default {
  color: #495057;
  background-color: #e9ecef;
}

.scope-badge {
  display: inline-block;
  padding: 4px 8px;
  font-size: 12px;
  font-weight: 500;
  border-radius: 4px;
}

.scope-badge.product-only {
  color: #2196f3;
  background-color: #e3f2fd;
}

.scope-badge.universal {
  color: #4caf50;
  background-color: #e8f5e8;
}

.scope-badge.default {
  color: #495057;
  background-color: #e9ecef;
}

.scope-info {
  padding: 8px;
  background-color: #f8f9fa;
  border-left: 4px solid #007bff;
  border-radius: 4px;
}

.scope-text {
  font-size: 14px;
  color: #666;
}

.association-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.association-counts {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.count-item {
  font-size: 12px;
  color: #666;
}

.manage-buttons {
  display: flex;
  gap: 8px;
}

.weight-display {
  display: flex;
  gap: 8px;
  align-items: center;
}

.weight-fill {
  height: 100%;
  background-color: #007bff;
  transition: width 0.3s ease;
}

.weight-value {
  min-width: 20px;
  font-size: 12px;
  font-weight: 600;
  color: #495057;
}

.product-count {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.association-count {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.count-number {
  font-weight: 600;
  color: #1a1a1a;
}

/* 开关样式 */
.switch {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;
}

.switch input {
  width: 0;
  height: 0;
  opacity: 0;
}

.slider {
  position: absolute;
  inset: 0;
  cursor: pointer;
  background-color: #ccc;
  border-radius: 24px;
  transition: 0.4s;
}

.slider::before {
  position: absolute;
  bottom: 3px;
  left: 3px;
  width: 18px;
  height: 18px;
  content: "";
  background-color: white;
  border-radius: 50%;
  transition: 0.4s;
}

input:checked + .slider {
  background-color: #007bff;
}

input:checked + .slider::before {
  transform: translateX(20px);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  cursor: pointer;
  background: none;
  border: none;
  border-radius: 4px;
  transition: all 0.2s;
}

.btn-icon svg {
  width: 16px;
  height: 16px;
  color: #666;
}

.btn-icon:hover {
  background-color: #f8f9fa;
}

.btn-icon:hover svg {
  color: #007bff;
}

.btn-icon.danger:hover {
  background-color: #f8d7da;
}

.btn-icon.danger:hover svg {
  color: #dc3545;
}

/* 批量操作栏 */
.batch-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-top: 1px solid #dee2e6;
}

.batch-actions-inline {
  display: flex;
  gap: 8px;
  margin-right: 16px;
}

.selected-count {
  font-size: 14px;
  color: #495057;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

/* 空状态 */
.empty-state {
  padding: 48px 24px;
  text-align: center;
}

.empty-icon {
  width: 48px;
  height: 48px;
  margin: 0 auto 16px;
  color: #ccc;
}

.empty-state h3 {
  margin: 0 0 8px;
  font-size: 18px;
  color: #1a1a1a;
}

.empty-state p {
  margin: 0;
  color: #666;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #1a1a1a;
}

.btn-close svg {
  width: 20px;
  height: 20px;
  color: #666;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #1a1a1a;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgb(0 123 255 / 25%);
}

.confirm-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  margin: 0 auto 16px;
  background-color: #f8d7da;
  border-radius: 50%;
}

.confirm-icon svg {
  width: 24px;
  height: 24px;
  color: #dc3545;
}

.confirm-modal h3 {
  margin: 0 0 12px;
  font-size: 18px;
  color: #1a1a1a;
}

.confirm-modal p {
  margin: 0 0 24px;
  line-height: 1.5;
  color: #666;
}

.product-info h4 {
  margin: 0 0 4px;
  font-size: 14px;
  color: #1a1a1a;
}

.product-info p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.associated-tag .icon {
  width: 12px;
  height: 12px;
}

.stats-section h4 {
  margin: 0 0 16px;
  color: #1a1a1a;
}

.weight-bar {
  flex: 1;
  height: 8px;
  overflow: hidden;
  background-color: #e9ecef;
  border-radius: 4px;
}
</style>
